<?php

namespace App\Http\Controllers\Home;

use App\Models\Article;
use App\Models\Cases;
use App\Models\Comment;
use App\Models\Tag;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class IndexController extends Controller
{
    public function __construct()
    {
        $config = DB::table("configs")->get();
        $configs = array_column(_toArray($config),"value","name");
        view()->share("configs",$configs);
    }

    public function base()
    {
        // 导航栏
        $navi = new \App\Models\Type;
        $naviData = $navi->getNavi();
        return array('naviData'=>$naviData);
    }

    // 首页
	public function index()
	{
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();
        // 文章点击排行
        $articleClick = $common->articleClick();
        // 本栏推荐
        $articlePraise = $common->articlePraise();
        // tags列表信息
        $tagsData = $common->getTags();
        // 专栏
        $casesData = DB::table("cases")->orderBy("weight","desc")->limit(5)->get();
        // 特别推荐
        $tj_data = DB::table('articles')->where('flag', 'like', '%特荐%')->limit(6)->get();
        // 一级栏目
        $ln_article=$head_type = DB::table('types')->where("parent_id",0)->orderBy('weight', 'desc')->limit(5)->get();
        $ln_article = json_decode(json_encode($ln_article), true);
//        dump($ln_article);

        $ln_article_arr = array();
        foreach($ln_article as $k=>$v){
//            $sql = DB::table('articles')->select("articles.*")->leftJoin('types AS b', 'articles.type_id', '=', 'b.id')->whereRaw("FIND_IN_SET({$v['id']},blog_b.path)")->orderBy('id', 'desc')->limit(5)->toSql();
//            dd($sql);
            $ln_article_arr[$k] = DB::table('articles')->select("articles.*")->leftJoin('types AS b', 'articles.type_id', '=', 'b.id')->whereRaw("FIND_IN_SET({$v['id']},blog_b.path)")->orderBy('id', 'desc')->limit(5)->get();
        }
        //$ln_article_arr = json_decode(json_encode($ln_article_arr), true);
//        dump($ln_article_arr);

        $article = new \App\Models\Article();
        // 最新文章
        $data = $article->orderBy('id', 'desc')->limit(22)->get();

        $assign = compact('naviData', 'articleClick', 'articlePraise', 'tagsData', 'data', 'tj_data', 'head_type', 'ln_article_arr','casesData');
		return view('/home/index/index', $assign);
	}

    /**
     * 栏目页
     * @param $id
     * @return mixed
     */
    public function type($id)
    {
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();
        // 文章点击排行
        $articleClick = $common->articleClick($id);
        // 本栏推荐
        $articlePraise = $common->articlePraise($id);
        // tags列表信息
        $tagsData = $common->getTags();
        // 当前栏目信息
        $typeData = DB::table('types')->find($id);
        // 当前栏目文章
        $listData = DB::table("articles as a")->select(DB::raw("blog_a.*,blog_b.name AS type_name,blog_u.nickname,blog_u.face"))
            ->leftJoin('types AS b', 'a.type_id', '=', 'b.id')
            ->leftJoin('users AS u', 'a.user_id', '=', 'u.id')
            ->where('a.type_id', $id)
            ->orWhereRaw(" blog_b.path like '%,".$id."%'")
            ->orderBy('a.id', 'desc')->paginate(10);

        //{{ $v->type_name }}
        //  测试使用模型关联取值
        //$model = new \App\Models\Article;
        //$listData = $model->orderBy('id', 'desc')->paginate(10);
        //{{ $v->types->name }}

        $assign = compact('typeData', 'listData', 'naviData', 'listData', 'articleClick', 'articlePraise', 'tagsData');

        return view('home/index/type',$assign);
    }

    /**
     * 关键字搜索页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function search(Request $request)
    {
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();
        // 文章点击排行
        $articleClick = $common->articleClick();
        // 本栏推荐
        $articlePraise = $common->articlePraise();
        // tags列表信息
        $tagsData = $common->getTags();

        // 当前栏目文章
        $listData = DB::table("articles AS a")->select(DB::raw("blog_a.*,blog_b.name AS type_name,blog_u.nickname,blog_u.face"))
            ->leftJoin('types AS b', 'a.type_id', '=', 'b.id')
            ->leftJoin('users AS u', 'a.user_id', '=', 'u.id')
            ->where(function($query) use ($request){
                if(!empty($request->keyword)){
                    $query->where('a.title', 'like', "%$request->keyword%");
                }
            })
            ->orderBy('a.id', 'desc')->paginate(10);

        $assign = compact('listData', 'naviData', 'listData', 'articleClick', 'articlePraise', 'tagsData', 'request');

        return view('home/index/search',$assign);
    }

    /**
     * 标签tag搜索页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function tag(Request $request,$id)
    {
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();
        // 文章点击排行
        $articleClick = $common->articleClick();
        // 本栏推荐
        $articlePraise = $common->articlePraise();
        // tags列表信息
        $tagsData = $common->getTags();

        // 当前标签下的文章
        $model = new \App\Models\Tag();
        $tag = $model->find($id);
        $listData = $tag->articles()->orderBy('id', 'desc')->paginate(10);

        $assign = compact('listData', 'naviData', 'listData', 'articleClick', 'articlePraise', 'tagsData', 'request', 'tag');

        return view('home/index/tag',$assign);
    }

    /**
     * tags标签列表页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function tags()
    {
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();

        $tags = new \App\Models\Tag();
        $data = $tags->select("*",(DB::raw('(SELECT COUNT(*) FROM blog_article_tags WHERE blog_article_tags.tag_id = blog_tags.id) AS num')))->orderBy('weight', 'desc')->get();

        $url = "/tag/";
        $title = "网站标签";
        $assign = compact('naviData', 'data','url','title');
        return view('home/index/tags',$assign);
    }

    /**
     * cases专栏列表页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function cases()
    {
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();

        $data = DB::table("cases")->select("*",(DB::raw('(SELECT COUNT(*) FROM blog_articles WHERE blog_cases.id = blog_articles.case_id) AS num')))->orderBy('weight', 'desc')->get();

        $url = "/getcase/";
        $title = "专栏列表";
        $assign = compact('naviData', 'data','url','title');
        return view('home/index/tags',$assign);
    }
    /**
     * 标签tag搜索页
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getcase(Request $request,$id)
    {
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();
        // 文章点击排行
        $articleClick = $common->articleClick();
        // 本栏推荐
        $articlePraise = $common->articlePraise();
        // tags列表信息
        $tagsData = $common->getTags();

        // 当前标签下的文章
        $model = new Article();
        $listData = $model->where("case_id",$id)->orderBy('id', 'desc')->paginate(10);

        $assign = compact('listData', 'naviData', 'listData', 'articleClick', 'articlePraise', 'tagsData', 'request');

        return view('home/index/tag',$assign);
    }

    /**
     * 文章页
     * @param Request $request
     * @param $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws \Exception
     */
    public function article(Request $request,$id)
    {
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();

        // tags列表信息
        $tagsData = $common->getTags();

        // 当前文章信息
        $articleData = DB::table("articles AS a")->select(DB::raw("blog_a.*,blog_b.name AS type_name,blog_u.nickname,blog_u.face"))
            ->leftJoin('types AS b', 'a.type_id', '=', 'b.id')
            ->leftJoin('users AS u', 'a.user_id', '=', 'u.id')
            ->where('a.id', $id)
            ->first();

        // 文章点击排行
        $articleClick = $common->articleClick($articleData->type_id);
        // 本栏推荐
        $articlePraise = $common->articlePraise($articleData->type_id);

        // 相关文章（调用最新的）
        $newArticleData = DB::table('articles')->where('type_id', $articleData->type_id)->orderBy('id', 'desc')->limit(4)->get();

        // 随机图文
        $articleTw = DB::table('articles')->where('picname', '!=', '')->orderBy('id', 'desc')->limit(4)->get();

        // 获取tags信息
        $article = new \App\Models\Article;
        $data = $article->find($id);
        $tags = $data->tags()->get();

        //获取上一篇文章
        $prev = $article->select('id', 'title')
            ->orderBy('created_at', 'desc')
            ->where('id', '<', $id)
            ->first();



        // 获取下一篇
        $next = $article::select('id', 'title')
            ->orderBy('created_at', 'asc')
            ->where('id', '>', $id)
            ->limit(1)
            ->first();

        // 获取评论
        $comment = (new Comment())->where('article_id',$id)->where('is_show','1')->orderBy('id','asc')->get();


        // 设置访问量
        // 同一个用户访问同一篇文章1分钟只增加1个访问量  使用 ip+id 作为 key 判别
        $ipAndId = 'articleRequestClick'.$request->ip().':'.$id;
        if (!Cache::has($ipAndId)) {
            cache([$ipAndId => ''], 1);
            // 文章点击量+1
            $data->increment('click');
        }

        // 面包屑导航
        $type_id = $data->type_id;
        $typeData = DB::table('types')->find($type_id);
        $crumbs = DB::table('types')
            ->whereRaw(" id IN ($typeData->path)")
            ->get();
        $crumbs[] = $typeData;
//        dd($crumbs);

        $assign = compact("crumbs", "articleData", "naviData", "tags", "prev", "next", 'articleClick' ,'articlePraise' ,'tagsData', 'newArticleData', 'articleTw','comment');
        return view('home/index/article',$assign);
    }

    /**
     * 时间轴
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function time()
    {
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();

        $data = DB::table('articles')->orderBy('id', 'desc')->paginate(25);

        $assign = compact('naviData', 'data');
        return view('home/index/time',$assign);
    }

    /**
     * 畅言留言板
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function message()
    {
        // 导航栏
        $common = new \App\Http\Controllers\Home\CommonController();
        $naviData = $common->getNavi();
        $assign = compact('naviData');
        return view('home/index/message', $assign);
    }

    /**
     * 用户点赞
     * @param Request $request
     * @param $id 文章ID
     * @return string
     * @throws \Exception
     */
    public function praise(Request $request,$id)
    {
        $article = new \App\Models\Article;
        $data = $article->find($id);
        $ipAndId = 'articlePraise' . $request->ip() . ':' . $id;
        if(!Cache::has($ipAndId)){
            cache([$ipAndId=>''],60);
            $data->increment('praise');
            $msg = array("status"=>1,"msg"=>$data->praise);
        } else {
            $msg = array("status"=>2,"msg"=>"一个小时只能赞一次哦");
        }
        return json_encode($msg);
    }

    public function comment(Request $request)
    {
        $data = $request->post();
        if(empty($data["article_id"])){
            $msg = array("status"=>2,"msg"=>"请求参数错误");
        }
        if(empty($data["nickname"])){
            $msg = array("status"=>2,"msg"=>"昵称不能为空");
        }
        if(empty($data["email"])){
            $msg = array("status"=>2,"msg"=>"email不能为空");
        }
        if(empty($data["content"])){
            $msg = array("status"=>2,"msg"=>"内容不能为空");
        }

        $ipAndId = 'articleComment' . $request->ip() . ':' . $data["article_id"];
        if(!Cache::has($ipAndId)){
            cache([$ipAndId=>''],60);
        } else {
            $msg = array("status"=>2,"msg"=>"一个分钟只能发布一次哦");
            // return json_encode($msg);
        }
        
        if(isset($msg['status']) && $msg['status'] == 2){
            return json_encode($msg);
        }

        $data['addtime'] = time();
        $re = (new Comment())->insert($data);
        if(!$re){
            $msg = array("status"=>2,"msg"=>"评论错误，请联系管理员");
            return json_encode($msg);
        }
        
        $msg = array("status"=>1,"msg"=>"评论成功");
        return json_encode($msg);
    }


}
